<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script>
import * as echarts from 'echarts'
import { listAhistory } from '@/api/system/ahistory'
import store from '@/store/index.js'

export default {
  name: 'UserRankStackedChart',
  data() {
    return {
      myChart: null,
      retryCount: 0,
      maxRetry: 3,
      currentUserId: null,
      dynamicData: null
    }
  },
  created() {
    if (store?.state?.user) {
      this.syncUserFromVuex()
      this.userWatcher = store.watch(
        state => state.user.id,
        (newId) => {
          if (newId && newId !== this.currentUserId) {
            this.currentUserId = newId
            this.fetchDataByPermission()
          }
        },
        { immediate: true }
      )
    } else {
      console.error('Vuex user模块未配置，请检查store.state.user是否存在')
    }
  },
  mounted() {
    this.initChart()
    this.currentUserId ? this.fetchDataByPermission() : this.retryFetch()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    if (this.userWatcher) this.userWatcher()
    if (this.myChart) this.myChart.dispose()
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // 从Vuex同步用户ID
    syncUserFromVuex() {
      const userState = store.state.user || {}
      this.currentUserId = userState.id || null
      console.log(`当前用户ID：${this.currentUserId}（${this.currentUserId === 1 ? '管理员-可查看所有用户' : '普通用户-仅查看自身'}）`)
    },

    // 初始化图表
    initChart() {
      const chartDom = this.$refs.chartRef
      if (!chartDom) return
      this.myChart = echarts.init(chartDom)
      this.myChart.setOption({
        title: { 
          text: this.getChartTitle('加载中'), 
          left: 'center', 
          textStyle: { fontSize: 14 } 
        },
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
        legend: { top: 40, left: 'center', data: [], pageButtonPosition: 'right' },
        grid: { left: '5%', right: '5%', bottom: '25%', top: '15%', containLabel: true },
        xAxis: { 
          type: 'category', 
          data: [],
          axisLabel: { rotate: 45, interval: 0, fontSize: 11, color: '#666' } 
        },
        yAxis: { 
          type: 'category', 
          data: [],
          axisLabel: { fontSize: 11, color: '#666' } 
        },
        series: [],
        dataZoom: [
          { type: 'inside', xAxisIndex: 0, start: 0, end: 100 },
          { type: 'slider', xAxisIndex: 0, bottom: 30, height: 8, backgroundColor: '#f5f5f5' }
        ]
      })
    },

    // 按权限请求数据
    async fetchDataByPermission() {
      try {
        // 核心权限控制：userId=1查询所有用户，其他用户查询自身
        const requestParams = this.currentUserId === 102 ? {} : { userId: this.currentUserId }
        console.log(`请求参数：${JSON.stringify(requestParams)}`);
        
        const res = await listAhistory(requestParams)
        
        if (res.code === 200 && Array.isArray(res.rows)) {
          this.dynamicData = res
          const userCount = [...new Set(res.rows.map(item => item.userId))].length
          console.log(`接口返回：共${res.total}条记录，涉及${userCount}个用户`);
          this.renderStackedChart(res.rows)
        } else {
          throw new Error(`接口返回异常：${res.msg || '数据格式错误'}`)
        }
      } catch (err) {
        console.error('数据请求失败：', err.message);
        this.myChart.setOption({
          title: { 
            text: `加载失败：${err.message}`, 
            left: 'center', 
            textStyle: { color: '#f56c6c' } 
          }
        })
      }
    },

    // 重试请求
    retryFetch() {
      if (this.retryCount >= this.maxRetry) {
        this.myChart.setOption({
          title: { 
            text: '未获取到用户身份，请登录后刷新', 
            left: 'center', 
            textStyle: { color: '#f56c6c' } 
          }
        })
        return
      }
      this.retryCount++
      setTimeout(() => {
        this.syncUserFromVuex()
        this.currentUserId ? this.fetchDataByPermission() : this.retryFetch()
      }, 1500)
    },

    // 渲染堆叠面积图
    renderStackedChart(rows) {
      // 提取维度数据
      const xAxisData = this.getSortedReasons(rows)
      const yAxisData = this.getSortedRanks(rows)
      const allUserIds = [...new Set(rows.map(item => item.userId))].sort((a, b) => a - b)

      // 构建系列数据
      const series = allUserIds.map(userId => {
        const seriesData = xAxisData.flatMap(reason => {
          return yAxisData.map(rank => {
            const count = rows.filter(item => 
              item.userId === userId && item.reason === reason && item.beforeRank === rank
            ).length
            return count > 0 ? count : 0
          })
        })

        return {
          name: `用户ID:${userId}`,
          type: 'line',
          stack: 'Total',
          smooth: true,
          lineStyle: { width: 1.2, opacity: 0.7 },
          showSymbol: true,
          symbol: 'circle',
          symbolSize: 6,
          areaStyle: { opacity: 0.8 },
          color: this.getUniqueColorByUserId(userId),
          data: seriesData,
          emphasis: { focus: 'series' }
        }
      })

      // 更新图表配置
      this.myChart.setOption({
        title: {
          text: this.getChartTitle('完成'),
          left: 'center',
          textStyle: { fontSize: 16, fontWeight: 500, color: '#333' },
          subtext: this.getChartSubtext(rows),
          subtextStyle: { fontSize: 12, color: '#909399' }
        },
        tooltip: {
          padding: 12,
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#eee',
          borderWidth: 1,
          boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
          formatter: (params) => {
            if (!params.length) return ''
            const firstParam = params[0]
            const totalCount = params.reduce((sum, param) => sum + param.value, 0)
            const reasonIndex = Math.floor(firstParam.dataIndex / yAxisData.length)
            const rankIndex = firstParam.dataIndex % yAxisData.length
            const currentReason = xAxisData[reasonIndex]
            const currentRank = yAxisData[rankIndex]
            const currentUserId = Number(firstParam.seriesName.split(':')[1])
            const matchItem = rows.find(item => 
              item.userId === currentUserId && item.reason === currentReason && item.beforeRank === currentRank
            )

            let tooltipHtml = `<div style="min-width:300px">
              <div style="font-weight:500; margin-bottom:8px; color:#333">
                事件原因：${currentReason} | 变更前段位：${currentRank}
              </div>
              <div style="margin-bottom:6px">总记录次数：<span style="color:#409EFF; font-weight:500">${totalCount}</span> 次</div>
              <div style="border-top:1px dashed #eee; padding-top:6px; margin-top:4px">当前用户详情：</div>
              <div style="margin-top:4px; font-size:12px">用户ID：${currentUserId}</div>
            `

            if (matchItem) {
              tooltipHtml += `
                <div style="margin-top:2px; font-size:12px">变更类型：${matchItem.changeType}</div>
                <div style="margin-top:2px; font-size:12px">变更后段位：${matchItem.afterRank}</div>
                <div style="margin-top:2px; font-size:12px">操作时间：${matchItem.createTime}</div>
                <div style="margin-top:2px; font-size:12px">记录ID：${matchItem.id}</div>
              `
            } else {
              tooltipHtml += `<div style="margin-top:2px; font-size:12px">当前用户无此记录</div>`
            }

            return tooltipHtml + `</div>`
          }
        },
        legend: {
          data: allUserIds.map(id => `用户ID:${id}`),
          top: 60,
          left: 'center',
          textStyle: { fontSize: 12, color: '#666' },
          itemWidth: 12,
          itemHeight: 12,
          pageButtonItemGap: 5,
          pageButtonGap: 10,
          pageIcons: { next: 'M0,0L8,4L0,8Z', prev: 'M8,0L0,4L8,8Z' },
          pageIconSize: 8,
          pageTextStyle: { fontSize: 10, color: '#999' }
        },
        xAxis: {
          data: xAxisData,
          axisLabel: {
            rotate: 45,
            interval: 0,
            formatter: (val) => val.length > 18 ? `${val.slice(0,18)}...` : val,
            color: '#666',
            fontSize: 11
          },
          axisLine: { lineStyle: { color: '#eee' } },
          axisTick: { lineStyle: { color: '#eee' } },
          splitLine: { show: false }
        },
        yAxis: {
          data: yAxisData,
          axisLabel: {
            formatter: (val) => val.length > 12 ? `${val.slice(0,12)}...` : val,
            color: '#666',
            fontSize: 11
          },
          axisLine: { lineStyle: { color: '#eee' } },
          axisTick: { lineStyle: { color: '#eee' } },
          splitLine: { lineStyle: { color: '#f5f5f5' } }
        },
        series: series
      })
    },

    // 生成图表标题
    getChartTitle(status) {
      if (status === '加载中') {
        return this.currentUserId === 1 
          ? '所有用户段位与事件原因堆叠面积图（加载中）' 
          : `用户ID:${this.currentUserId} 段位与事件原因堆叠面积图（加载中）`
      }
      return this.currentUserId === 1 
        ? `所有用户段位与事件原因堆叠面积图（共${[...new Set(this.dynamicData.rows.map(item => item.userId))].length}个用户）` 
        : `用户ID:${this.currentUserId} 段位与事件原因堆叠面积图`
    },

    // 生成图表副标题
    getChartSubtext(rows) {
      const timeRange = this.getDateRange(rows)
      return this.currentUserId === 1 
        ? `总记录数：${this.dynamicData.total}条 | 时间范围：${timeRange} | 覆盖用户数：${[...new Set(rows.map(item => item.userId))].length}个` 
        : `总记录数：${this.dynamicData.total}条 | 时间范围：${timeRange}`
    },

    // 按时间排序事件原因
    getSortedReasons(rows) {
      const reasonFirstTimeMap = {}
      rows.forEach(item => {
        if (!reasonFirstTimeMap[item.reason] || new Date(item.createTime) < new Date(reasonFirstTimeMap[item.reason])) {
          reasonFirstTimeMap[item.reason] = item.createTime
        }
      })
      return [...new Set(rows.map(item => item.reason))].sort((a, b) => 
        new Date(reasonFirstTimeMap[a]) - new Date(reasonFirstTimeMap[b])
      )
    },

    // 按业务逻辑排序段位
    getSortedRanks(rows) {
      const baseRankOrder = [
        '秩序白银 IV', '荣耀黄金 I', '荣耀黄金 IV',
        '至尊星耀II', '至尊星耀III', '至尊星耀V',
        '永恒钻石I', '永恒钻石II', '永恒钻石III', '永恒钻石IV', '永恒钻石V'
      ]
      return [...new Set(rows.map(item => item.beforeRank))].sort((a, b) => {
        const idxA = baseRankOrder.indexOf(a) === -1 ? 999 : baseRankOrder.indexOf(a)
        const idxB = baseRankOrder.indexOf(b) === -1 ? 999 : baseRankOrder.indexOf(b)
        return idxA - idxB
      })
    },

    // 计算数据时间范围
    getDateRange(rows) {
      const times = rows.map(item => new Date(item.createTime))
      const minTime = new Date(Math.min(...times))
      const maxTime = new Date(Math.max(...times))
      const format = (date) => `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
      return `${format(minTime)} 至 ${format(maxTime)}`
    },

    // 为不同用户ID生成唯一颜色
    getUniqueColorByUserId(userId) {
      const colorPool = [
        '#409EFF', '#67C23A', '#F56C6C', '#FF9F43', '#9C27B0',
        '#17C3B2', '#FF6B6B', '#4ECDC4', '#FFE66D', '#1A535C',
        '#FF8A80', '#82B1FF', '#B9F6CA', '#FFFF8D', '#FF80AB'
      ]
      return colorPool[userId % colorPool.length]
    },

    // 窗口大小变化时重绘图表
    handleResize() {
      this.myChart && this.myChart.resize()
    }
  }
}
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 550px;
  margin: 10px auto 0;
  background-color: #fafafa;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
</style>
